//请求响应数据类型
interface Data<T>{
    code:number,
    msg:string,
    data:T
}

/**
 * 引入axios
 * 对axios进行二次封装
 */
import Axios from "axios";
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig, AxiosError, AxiosRequestConfig } from "axios";


//引入用户仓库
import useUserStore from "@/store/user";




const request:AxiosInstance = Axios.create({
    baseURL:"/api",
    timeout:5000
});


//请求拦截器
request.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    const userStore = useUserStore();
    //请求头携带token
    if(userStore.userToken) {
        config.headers.token = userStore.userToken;
    }
    return config;
})


//响应拦截器
request.interceptors.response.use((response:AxiosResponse) => {
    return response.data;
},(error:AxiosError) => {
    return Promise.reject(error);
});





//导出部分封装的请求方法
export const http = {
    get<T = any>(url:string,config?:InternalAxiosRequestConfig):Promise<T>{
        return request.get(url,config);
    },

    post<T = any>(url:string,data?:object,config?:InternalAxiosRequestConfig):Promise<T>{
        return request.post(url,data,config);
    }
}

//导出对request进行ts封装的方法
export function requestHttp<T = any>(config:AxiosRequestConfig):Promise<Data<T>> {
    return request(config);
}



//默认导出axios实例对象
export default request;